/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.controller;

import com.googlecode.bambole.controller.util.ConfigurationUtil;
import com.googlecode.bambole.domain.Organization;
import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.PaginationUtil;
import com.googlecode.bambole.domain.Industry;
import com.googlecode.bambole.domain.User;
import com.googlecode.bambole.facade.OrganizationFacade;
import com.googlecode.bambole.util.CnpjCpfUtil;
import com.googlecode.bambole.util.EntryFormatUtil;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.inject.Inject;

/**
 *
 * @author Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 */
@Named("organizationController")
@SessionScoped
public class OrganizationController implements Serializable {

    private Organization current;
    private DataModel items = null;

    @EJB
    private com.googlecode.bambole.facade.OrganizationFacade ejbFacade;

    @Inject
    private com.googlecode.bambole.controller.PersonController personController;

    @Inject
    private com.googlecode.bambole.controller.AddressController addressController;

    @Inject
    private com.googlecode.bambole.controller.IndustryController industryController;

    @Inject
    private com.googlecode.bambole.controller.OrganizationNoteController organizationNoteController;

    private PaginationUtil pagination;
    private Industry industrySearch;
    private String query;
    private int selectedItemIndex;
    private int recordCount;
    private boolean searchMode = false;

    public OrganizationController() {
    }

    public Organization getSelected() {
        if (current == null) {
            current = new Organization();
        }
        return current;
    }

    public void setSelected(Organization current) {
        this.current = current;
    }

    private OrganizationFacade getFacade() {
        return ejbFacade;
    }

    public boolean isPaginationFromSearch() {
        return !getQuery().equals(getDefaultQuery());
    }

    public PaginationUtil getPagination() {
        if (pagination == null) {
            pagination = new PaginationUtil(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count(getQuery(), industrySearch);
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}, getQuery(), industrySearch));
                }
            };
        }
        return pagination;
    }

    public String refreshList() {
        industrySearch = null;
        query = null;
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareList() {
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String prepareView() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        recordCount = getFacade().count(getQuery(), industrySearch);

        return "view.xhtml?faces-redirect=true";
    }

    public String prepareCreate() {

        searchMode = false;

        current = new Organization();
        current.setIndustry(industryController.getDefaultItem());

        return "create.xhtml?faces-redirect=true";
    }

    public String create() {

        if (!validateRecord()) {
            return null;
        }

        Date date = new Date();
        User user = (User) JsfUtil.getSessionParameter("user");
        current.setCreated(date);
        current.setCreatedBy(user);
        current.setUpdated(date);
        current.setUpdatedBy(user);

        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String prepareEdit() {
        searchMode = false;
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));

            return null;
        }

        return "edit.xhtml?faces-redirect=true";
    }

    public String update() {

        if (!validateRecord()) {
            return null;
        }

        current.setUpdated(new Date());
        current.setUpdatedBy((User) JsfUtil.getSessionParameter("user"));

        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordSaved"));
            return "view.xhtml?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
            return null;
        }
    }

    public String destroy() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }
        performDestroy();
        recreatePagination();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("RecordDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("PersistenceError"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "list.xhtml?faces-redirect=true";
    }

    public Organization getOrganization(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    public void setSelectedItemIndex(int selectedItemIndex) {
        this.selectedItemIndex = selectedItemIndex + pagination.getPageFirstItem();
    }

    public boolean isHasNextRecord() {
        return selectedItemIndex + 2 <= recordCount;
    }

    public boolean isHasPreviousRecord() {
        return selectedItemIndex > 0;
    }

    public String nextItem() {

        selectedItemIndex++;

        if (selectedItemIndex < recordCount) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    public String previousItem() {

        selectedItemIndex--;

        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex}, getQuery()).get(0);
        }

        return "view.xhtml?faces-redirect=true";
    }

    private boolean validateRecord() {

        boolean retVal = true;

        if (!getFacade().isNameUnique(current.getName(), current.getId() == null ? -1 : current.getId())) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NameAlreadyExists"));

            retVal = false;
        }

        if (current.getTaxId1() != null && !current.getTaxId1().isEmpty()) {

            if (ConfigurationUtil.isCheckCnpjCpf()) {
                String cnpjCpf = CnpjCpfUtil.checkCnpjCpf(current.getTaxId1());

                if (cnpjCpf.equals("*")) {
                    JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("TaxId1Invalid"));

                    retVal = false;
                } else {
                    current.setTaxId1(cnpjCpf);
                }
            }

            if (!getFacade().isTaxId1Unique(current.getTaxId1(), current.getId() == null ? -1 : current.getId())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("TaxId1AlreadyExists"));

                retVal = false;
            }

        }

        if (current.getWebAddress() != null && !current.getWebAddress().isEmpty()) {
            if (!EntryFormatUtil.isWebAddressFormatValid(current.getWebAddress())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidWebAddress"));

                retVal = false;
            }
        }

        if (current.getAlternateWebAddress() != null && !current.getAlternateWebAddress().isEmpty()) {
            if (!EntryFormatUtil.isWebAddressFormatValid(current.getAlternateWebAddress())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidAlternateWebAddress"));

                retVal = false;
            }

            if (current.getWebAddress() != null && !current.getWebAddress().isEmpty()) {
                if (current.getWebAddress().equals(current.getAlternateWebAddress())) {
                    JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("WebAddressAndAlternateWebAddressMustBeDifferent"));

                    retVal = false;
                }
            }
        }

        if (current.getEmailAddress() != null && !current.getEmailAddress().isEmpty()) {

            if (!EntryFormatUtil.isEmailAddressFormatValid(current.getEmailAddress())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidEmailAddress"));

                retVal = false;
            }

            if (!getFacade().isEmailAddressUnique(current.getEmailAddress(), current.getId() == null ? -1 : current.getId())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("EmailAddressAlreadyExists"));

                retVal = false;
            }
        }

        if (current.getAlternateEmailAddress() != null && !current.getAlternateEmailAddress().isEmpty()) {

            if (!EntryFormatUtil.isEmailAddressFormatValid(current.getAlternateEmailAddress())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidAlternateEmailAddress"));

                retVal = false;
            }

            if (!getFacade().isEmailAddressUnique(current.getAlternateEmailAddress(), current.getId() == null ? -1 : current.getId())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("AlternateEmailAddressAlreadyExists"));

                retVal = false;
            }

            if (current.getEmailAddress() != null && !current.getEmailAddress().isEmpty()) {
                if (current.getEmailAddress().equals(current.getAlternateEmailAddress())) {
                    JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("EmailAddressAndAlternateEmailAddressMustBeDifferent"));

                    retVal = false;
                }
            }
        }

        if (current.getTelephoneNumber() != null && !current.getTelephoneNumber().isEmpty()) {
            if (!EntryFormatUtil.isTelephoneNumberFormatValid(current.getTelephoneNumber())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidTelephoneNumber"));

                retVal = false;
            }
        }

        if (current.getAlternateTelephoneNumber() != null && !current.getAlternateTelephoneNumber().isEmpty()) {
            if (!EntryFormatUtil.isTelephoneNumberFormatValid(current.getAlternateTelephoneNumber())) {
                JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("InvalidAlternateTelephoneNumber"));

                retVal = false;
            }

            if (current.getTelephoneNumber() != null && !current.getTelephoneNumber().isEmpty()) {
                if (current.getTelephoneNumber().equals(current.getAlternateTelephoneNumber())) {
                    JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("TelephoneNumberAndAlternateTelephoneNumberMustBeDifferent"));

                    retVal = false;
                }
            }
        }

        if (!current.getIndustry().isEnabled()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("DisabledIndustrySelected"));
        }

        if (current.getAddressList() == null || current.getAddressList().isEmpty()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("OrganizationHasNoAddress"));
        }

        if (current.getPersonList() == null || current.getPersonList().isEmpty()) {
            JsfUtil.addWarningMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("OrganizationHasNoPerson"));
        }

        return retVal;
    }

    private String getQuery() {
        return query == null ? getDefaultQuery() : query;
    }

    private String getDefaultQuery() {
        return "SELECT o FROM Organization o";
    }

    public String prepareSearch() {
        searchMode = true;
        current = new Organization();
        return "search.xhtml?faces-redirect=true";
    }

    public String performSearch() {

        boolean queryAddAnd = false;

        searchMode = false;

        query = getDefaultQuery();

        if ((current.getName() != null && !current.getName().isEmpty())
                || (current.getLegalName() != null && !current.getLegalName().isEmpty())
                || (current.getTaxId1() != null && !current.getTaxId1().isEmpty())
                || (current.getTaxId2() != null && !current.getTaxId2().isEmpty())
                || (current.getTaxId2() != null && !current.getTaxId2().isEmpty())
                || (current.getWebAddress() != null && !current.getWebAddress().isEmpty())
                || (current.getAlternateWebAddress() != null && !current.getAlternateWebAddress().isEmpty())
                || (current.getEmailAddress() != null && !current.getEmailAddress().isEmpty())
                || (current.getAlternateEmailAddress() != null && !current.getAlternateEmailAddress().isEmpty())
                || (current.getTelephoneNumber() != null && !current.getTelephoneNumber().isEmpty())
                || (current.getAlternateTelephoneNumber() != null && !current.getAlternateTelephoneNumber().isEmpty())
                || (current.getAdditionalInfo() != null && !current.getAdditionalInfo().isEmpty())
                || (current.getIndustry() != null)) {

            query = query + " WHERE ";

            if (current.getName() != null && !current.getName().isEmpty()) {
                queryAddAnd = true;
                query = query + "o.name LIKE \'%" + current.getName() + "%\'";
            }

            if (current.getLegalName() != null && !current.getLegalName().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.legalName LIKE \'%" + current.getLegalName() + "%\'";
            }

            if (current.getTaxId1() != null && !current.getTaxId1().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.TaxId1 LIKE \'%" + current.getTaxId1() + "%\'";
            }

            if (current.getTaxId2() != null && !current.getTaxId2().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.TaxId2 LIKE \'%" + current.getTaxId2() + "%\'";
            }

            if (current.getTaxId3() != null && !current.getTaxId3().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.TaxId3 LIKE \'%" + current.getTaxId3() + "%\'";
            }

            if (current.getWebAddress() != null && !current.getWebAddress().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.webAddress LIKE \'%" + current.getWebAddress() + "%\'";
            }

            if (current.getAlternateWebAddress() != null && !current.getAlternateWebAddress().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.alternateWebAddress LIKE \'%" + current.getAlternateWebAddress() + "%\'";
            }

            if (current.getEmailAddress() != null && !current.getEmailAddress().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.emailAddress LIKE \'%" + current.getEmailAddress() + "%\'";
            }

            if (current.getAlternateEmailAddress() != null && !current.getAlternateEmailAddress().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.alternateEmailAddress LIKE \'%" + current.getAlternateEmailAddress() + "%\'";
            }

            if (current.getTelephoneNumber() != null && !current.getTelephoneNumber().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.telephoneNumber LIKE \'%" + current.getTelephoneNumber() + "%\'";
            }

            if (current.getAlternateTelephoneNumber() != null && !current.getAlternateTelephoneNumber().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.alternateTelephoneNumber LIKE \'%" + current.getAlternateTelephoneNumber() + "%\'";
            }

            if (current.getAdditionalInfo() != null && !current.getAdditionalInfo().isEmpty()) {
                if (queryAddAnd) {
                    query = query + " AND ";
                } else {
                    queryAddAnd = true;
                }
                query = query + "o.additionalInfo LIKE \'%" + current.getAdditionalInfo() + "%\'";
            }

            if (current.getIndustry() != null) {
                if (queryAddAnd) {
                    query = query + " AND ";
                }
                query = query + "o.industry = :industry";
                industrySearch = current.getIndustry();
            }

        }

        recreatePagination();
        recreateModel();

        return "list.xhtml?faces-redirect=true";
    }

    public SelectItem[] getItemsAvailableSelectOne(boolean includeDisabledItems) {

        List<Organization> organizationList;

        if (includeDisabledItems) {
            organizationList = getFacade().findAll();
        } else {
            organizationList = getFacade().findEnabled();
        }

        SelectItem[] organizations = new SelectItem[organizationList.size() + 1];

        organizations[0] = new SelectItem(null, null);

        int i = 1;
        for (Organization organization : organizationList) {
            organizations[i++] = new SelectItem(organization, organization.getNameWithDisabledFormatting());
        }

        return organizations;
    }

    public SelectItem[] getFreightItemsAvailableSelectOne(boolean includeDisabledItems) {

        List<Organization> freightOrganizationList;

        if (includeDisabledItems) {
            freightOrganizationList = getFacade().findAllFreightOrganization();
        } else {
            freightOrganizationList = getFacade().findEnabledFreightOrganization();
        }

        SelectItem[] freightOrganizations = new SelectItem[freightOrganizationList.size() + 1];

        freightOrganizations[0] = new SelectItem(null, null);

        int i = 1;
        for (Organization freightOrganization : freightOrganizationList) {
            freightOrganizations[i++] = new SelectItem(freightOrganization, freightOrganization.getNameWithDisabledFormatting());
        }

        return freightOrganizations;
    }

    public SelectItem[] getSelectIndustry() {
        return industryController.getItemsAvailableSelectOne(searchMode);
    }

    public String prepareAddressList() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        addressController.setCurrentOrganization(current);

        return "/app/address/list.xhtml?faces-redirect=true";
    }

    public String preparePersonList() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        personController.setCurrentOrganization(current);

        return "/app/person/list.xhtml?faces-redirect=true";
    }

    public String prepareNoteList() {
        if (current == null) {
            JsfUtil.addErrorMessage(ResourceBundle.getBundle("/bundle", JsfUtil.getLocale()).getString("NoRecordSelected"));
            return null;
        }

        organizationNoteController.setCurrentOrganization(current);

        return "/app/organization_note/list.xhtml?faces-redirect=true";
    }
}
